package common.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.Scanner;

import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.MessageBodyWriter;
import javax.ws.rs.ext.Provider;

import org.json.JSONArray;

/**
 * A reader and writer from string to {@link JSONArray}
 * 
 * @author Gal Lalouche
 */
@Provider
@Produces(MediaType.APPLICATION_JSON)
public class JSONArrayBodyReaderWriter implements MessageBodyWriter<JSONArray>, MessageBodyReader<JSONArray> {

	@Override
	public long getSize(JSONArray arg0, Class<?> arg1, Type arg2, Annotation[] arg3, MediaType arg4) {
		return -1;
	}

	@Override
	public boolean isWriteable(Class<?> arg0, Type arg1, Annotation[] arg2, MediaType arg3) {
		return arg0.equals(JSONArray.class);
	}

	@Override
	public void writeTo(JSONArray arg0, Class<?> arg1, Type arg2, Annotation[] arg3, MediaType arg4,
			MultivaluedMap<String, Object> arg5, OutputStream arg6) throws IOException {
		arg6.write(arg0.toString().getBytes());
	}

	@Override
	public boolean isReadable(Class<?> arg0, Type arg1, Annotation[] arg2, MediaType arg3) {
		return arg0.equals(JSONArray.class);
	}

	@Override
	public JSONArray readFrom(Class<JSONArray> arg0, Type arg1, Annotation[] arg2, MediaType arg3,
			MultivaluedMap<String, String> arg4, InputStream arg5) {
		try (Scanner scanner = new Scanner(arg5)) {
			String str = scanner.useDelimiter("\\A").next();
			return new JSONArray(str);
		}
	}
}
